package com.mspbots.cw.amqp.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.amqp.BaseReceiver;
import com.mspbots.cw.amqp.model.Company;
import com.mspbots.cw.amqp.model.ExceptionLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * CompaniesReceiver is com.mspbots.cw.amqp.receivers
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/7
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class CompaniesReceiver extends BaseReceiver {

    @RabbitListener(queues = "wise.companies")
    public void processMessage(JsonNode company) {
        try{
            log.debug("wise.companies tenant {} receiver is {}", company.get("tenantId"), company.get("id"));
            Company company1 = Company.builder()
                    .cwId(company.get("id").asInt())
                    .tenantId(company.get("tenantId").asInt())
                    .name(company.get("name").asText())
                    .updatedTime(LocalDateTime.parse(company.findValue("lastUpdated").asText(), DateTimeFormatter.ISO_DATE_TIME))
                    .extend(company)
                    .build();
            this.databaseClient.execute("select id from tenant_companies where tenant_id =:tenantId and cw_id =:cwId")
                    .as(Long.class)
                    .bind("tenantId", company1.getTenantId())
                    .bind("cwId", company1.getCwId())
                    .fetch().one()
                    .flatMap(id -> {
                        log.debug("Receiver companies tenant id:{},cw id:{}", company1.getTenantId(), company1.getCwId());
                        company1.setId(id);
                        company1.setSyncTime(LocalDateTime.now());
                        return this.databaseClient.update().table(Company.class).using(company1).fetch().rowsUpdated();
                    })
                    .switchIfEmpty(this.databaseClient.insert().into(Company.class).using(company1).fetch().rowsUpdated())
                    .subscribe(result -> log.debug("companies save is success {}", result),
                            err -> log.error("companies save or update is error,msg: {}", err.getMessage()));

//        super.messagingTemplate.convertAndSend("next-ticket.redis.companies",company1);
        }catch (Exception e){
            if (!ObjectUtils.isEmpty(company.get("tenantId"))){
                this.databaseClient.insert().into(ExceptionLog.class).using(
                        ExceptionLog.builder()
                                .tenantId(company.get("tenantId").asInt())
                                .name("wise.companies")
                                .status(500)
                                .type("wise.companies")
                                .msg(e.getMessage()+","+company.toString() )
                                .build()
                ).fetch().rowsUpdated().block(Duration.ofSeconds(10));
            }
        }

    }
}
